package com.example.zhinongbao.Fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.bumptech.glide.Glide;
import com.example.zhinongbao.R;
import com.example.zhinongbao.activity.MainActivity;
import com.example.zhinongbao.activity.NewsDetailActivity;
import com.example.zhinongbao.activity.PublishNewsActivity;
import com.example.zhinongbao.contract.SchoolContract;
import com.example.zhinongbao.presenter.SchoolPresenter;
import com.example.zhinongbao.provider.NewsDao;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class SchoolFragment extends Fragment implements SchoolContract.View {
    private ListView lvSchoolNews;
    private ImageView ivPublishNews;
    private Button btnSwitchToEmpty;
    private SchoolPresenter presenter;
    private List<NewsItem> newsList = new ArrayList<>();
    private NewsAdapter adapter;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        presenter = new SchoolPresenter(requireContext());
        presenter.attachView(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_school, container, false);
        initViews(view);
        setupListeners();
        return view;
    }

    private void initViews(View view) {
        lvSchoolNews = view.findViewById(R.id.lv_school_news);
        ivPublishNews = view.findViewById(R.id.iv_publish_news);
        btnSwitchToEmpty = view.findViewById(R.id.btn_switch_empty);
        adapter = new NewsAdapter();
        lvSchoolNews.setAdapter(adapter);
    }

    private void setupListeners() {
        ivPublishNews.setOnClickListener(v -> {
            Intent intent = new Intent(requireActivity(), PublishNewsActivity.class);
            startActivity(intent);
        });

        lvSchoolNews.setOnItemClickListener((parent, view, position, id) -> {
            NewsItem news = newsList.get(position);
            Intent intent = new Intent(requireActivity(), NewsDetailActivity.class);
            intent.putExtra("title", news.title);
            intent.putExtra("htmlContent", news.htmlContent);
            startActivity(intent);
        });

        btnSwitchToEmpty.setOnClickListener(v -> switchToFriendCircleFragment());
    }

    // 保留唯一的switchToFriendCircleFragment方法
    private void switchToFriendCircleFragment() {
        // 方案1：通过MainActivity的导航系统切换（推荐）
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).switchToFragment("friend_circle");
        }
        // 方案2：直接替换Fragment（备用）
        else {
            getParentFragmentManager().beginTransaction()
                    .setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
                    .replace(R.id.fl_content, new FriendCircleFragment())
                    .addToBackStack(null)
                    .commit();
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        presenter.getSchoolNews();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        presenter.detachView();
    }

    // Contract.View 接口实现
    @Override
    public void showSchoolNews(String[] newsTitles, String[] htmlContents, String[] imageUrls) {
        newsList.clear();
        for (int i = 0; i < newsTitles.length; i++) {
            newsList.add(new NewsItem(
                    newsTitles[i],
                    htmlContents[i],
                    imageUrls != null && i < imageUrls.length ? imageUrls[i] : null
            ));
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void showError(String message) {
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onPublishSuccess() {
        Toast.makeText(requireContext(), "发布成功", Toast.LENGTH_SHORT).show();
    }

    // 数据模型和适配器
    private static class NewsItem {
        String title;
        String htmlContent;
        String imageUrl;

        NewsItem(String title, String htmlContent, String imageUrl) {
            this.title = title;
            this.htmlContent = htmlContent;
            this.imageUrl = imageUrl;
        }
    }

    private class NewsAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return newsList.size();
        }

        @Override
        public NewsItem getItem(int position) {
            return newsList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(requireContext())
                        .inflate(R.layout.item_school_news, parent, false);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            NewsItem item = getItem(position);
            holder.tvTitle.setText(item.title);
            holder.tvContent.setText(getBriefContent(item.htmlContent));

            if (item.imageUrl != null && !item.imageUrl.isEmpty()) {
                Glide.with(holder.ivNews)
                        .load(item.imageUrl)
                        .placeholder(R.drawable.ic_image_placeholder)
                        .error(R.drawable.ic_broken_image)
                        .into(holder.ivNews);
            }

            return convertView;
        }

        private String getBriefContent(String html) {
            String plainText = html.replaceAll("<[^>]+>", "");
            return plainText.length() > 50
                    ? plainText.substring(0, 50) + "..."
                    : plainText;
        }

        class ViewHolder {
            TextView tvTitle;
            TextView tvContent;
            ImageView ivNews;

            ViewHolder(View view) {
                tvTitle = view.findViewById(R.id.tv_title);
                tvContent = view.findViewById(R.id.tv_content);
                ivNews = view.findViewById(R.id.iv_news);
            }
        }
    }
}